import { cfg } from './cfg.js';
import axios from 'axios';
import router from '../router'
import { v4 as uuidv4 } from "uuid";

export const getuser = async (uuid) => {
    let res;
    try {


        res = await axios.get(`${cfg.url2}api/closed_code/user`, {
            params: {
                type: 'info',
                token: cfg.token,
            },
        });

        //检查有没有报错
        if (res.status != 200) {
            return;
        }

        if (res.data.code == -1) {
            return;
        }

        cfg.role_limit = res.data?.count?.role_data;
        cfg.boss_count = res.data?.count?.boss_data;
        cfg.user = res.data.data;

        if (cfg.opid_loginbind == true) {
            cfg.opid_loginbind = false;
            if (cfg.opid_uuid == null) {
                alert('错误的uuid');
                return;
            }
            let res = await cfg.axios.get(`${cfg.url}`, {
                params: {
                    t: "v2/get",
                    t2: "os/qqend",
                    authkey: cfg.user?.authkey,
                    uid: cfg.user?.uid,
                    uuid: cfg.opid_uuid,
                },
            });
            if (res.data.code == 0) {
                alert('绑定登录成功');
            } else {
                alert('绑定失败' + res.data.msg);
            }
        }
    } catch (error) {
        cfg.alert3({
            message: `发生错误：${error.message}`,
            closeOnClickOverlay: true,
        });
    }
}

export const get_season = () => {
    if (cfg?.season == null) {
        axios.get(`${cfg.url}?t=get/gt/season_list`,)
            .then(response => {
                cfg.user = response.data;
            })
            .catch(err => {
                console.error(err);
                alert("未知错误请刷新" + err);
            });
    }
}

export const get_work_season = async () => {
    let res = await cfg.axios.get(`${cfg.url}`, {
        params: {
            t: "v2/get",
            t2: "admin/guild_work",
            t3: "getlist",
        },
    });
    if (res.data.code == 0) {
        return res.data.data;
    } else {
        cfg.alert3({
            message: `${res.data.msg}请尝试刷新页面`,
            closeOnClickOverlay: true,
        });
    }
}

export const load_avg = async (gid, level) => {
    await axios({
        method: 'get',
        url: `${cfg.url}?t=get/guild/damage_level`,
        params: {
            gid: gid,
            level: level ?? null,
            authkey: cfg.user?.authkey
        },
        responseType: 'json',
    })
        .then(response => {
            cfg.guild.avgdata = response.data;
        })
        .catch(err => {
            cfg.alert3({
                message: `${err}请尝试刷新页面`,
                closeOnClickOverlay: true,
            });
        });

};

export const getusername = (uid, arr) => {

    axios({
        method: 'get',
        url: `${cfg.url}?t=get/user/username`,
        params: {
            uid: uid,
        },
        responseType: 'json',
    })
        .then(response => {
            const data = response.data;
            if (data.code == -1) {
                arr.username = data.msg;
            } else {
                arr.username = data;
            }
        })
        .catch(err => {
            arr.username = "获取失败";
        });
};

export const get_guild_cdb = async (gid) => {
    try {
        const back = await cfg.mget({
            url: `${cfg.api}api/guild`,
            query: {
                type : 'get_cdb',
                guild_id:gid,
            },
        });
        if (back.code == 0) {
            return back.data;
        } else {
           throw new Error(back.msg);
        }
    } catch (error) {
        cfg.alert3({
            message: `${error.message}`,
            closeOnClickOverlay: true,
        });
    }
};

//获取角色图标
export const strtorole = (str) => {
    //对字符串进行逗号切割
    let sp = str.split(",");
    let sp2 = [];
    for (let i = 0; i < sp.length; i++) {
        if (cfg.role_name[sp[i]] != null) {
            if (cfg.role_name[sp[i]].icon == 'tanker.png') {
                sp[i] = '克雷格〔晋升〕';
            }
            if (cfg.role_name[sp[i]].icon == 'vampire_noble.png') {
                sp[i] = '克雷格〔晋升〕';
            }
            sp2.push(cfg.role_name[sp[i]].icon);
        } else {
            const arr = {
                code: -1,
                type: 'error',
                msg: '查询角色(' + sp[i] + ')不存在',
            };
            window.myFunction(arr);
            return false;
        }
    }
    return sp2;
};

export const get_boss = async (str) => {
    let res = await cfg.axios.get(`${cfg.url}`, {
        params: {
            t: "v2/get",
            t2: "admin/boss",
            t3: "getlist",
        },
    });
    if (res.data.code == 0) {
        cfg.bosslist = res.data.data;
        //把cfg.bosslist.name转为key
        cfg.bossnamelist = {};
        for (let i = 0; i < cfg.bosslist.length; i++) {
            cfg.bossnamelist[cfg.bosslist[i].name] = cfg.bosslist[i];
        }
    } else {
        cfg.alert3({
            message: `${res.data.msg}请尝试刷新页面`,
            closeOnClickOverlay: true,
        });
    }
};

export const getbossv2 = async (str) => {
    if (cfg.bosslist?.length >= 1) {
        return;
    }

    let res = await cfg.axios.get(`${cfg.url2}api/boss`, {
        params: {
            count: cfg.boss_count,
            d: 11451422,
        },
    });
    if (res.data.code == 0) {
        cfg.bosslist = res.data.data.data;
        //把cfg.bosslist.name转为key
        cfg.bossnamelist = {};
        for (let i = 0; i < cfg.bosslist.length; i++) {
            cfg.bossnamelist[cfg.bosslist[i].name] = cfg.bosslist[i];
            cfg.bossnamelist[cfg.bosslist[i].bname] = cfg.bosslist[i];
        }

    } else {
        cfg.alert3({
            message: `${res.data.msg}请尝试刷新页面`,
            closeOnClickOverlay: true,
        });
    }
};


export const getrole = async (re, hide, str) => {
    try {


        if (str == 'all' && cfg?.role?.[0]?.yc != null) {
            return;
        }
        if (cfg.role == null || re == true) {
            let str = '';
            if (re == true) {
                const rdid = uuidv4();
                str += `${rdid}`;
            }
            if (hide == true) {
                cfg.loadlist.role = {
                    name: "坎公角色库",
                    file: {
                        max: 0,
                    },
                    ok: true,
                };
            }

            const back = await cfg.mget({
                url: `${cfg.url2}api/role`,
                query: {
                    count: cfg.role_limit,
                    str,
                },
            });

            const res = back;



            if (res.code != 0) {
                throw new Error(res.msg);
                return;
            }
            cfg.role_name = {};
            cfg.role_icon = {};
            cfg.role = res.data.role;
            for (let index = 0; index < cfg.role.length; index++) {
                const d = cfg.role[index];
                if (d.mythicon != null) {
                    cfg.role_icon[d.icon] = d;
                    d.icon = d.mythicon;
                }
            }
            cfg.role_limit = res.data.count;
            //浅拷贝response.data
            const rd = Object.assign({}, cfg.role);

            //遍历重组key为角色名称，并去掉旧的key
            for (let i in rd) {
                cfg.role_name[rd[i].name] = rd[i];
                cfg.role_icon[rd[i].icon] = rd[i];
                //遍历rd[i].bname
                for (let j in rd[i].bname) {
                    cfg.role_name[rd[i].bname[j]] = rd[i];
                }
            }
            return cfg.role;
        }
    } catch (error) {
        console.error(error);
        cfg.alert3({
            message: `${error},${error.stack}`,
            closeOnClickOverlay: true,
        });
    }
};

export const funs = {

    qxlang(code) {
        switch (code) {
            case "idc":
                return '权限用户组：攻略组、管理员';
            default:
                return false;
        }
    },
    ckqx(type) {
        switch (type) {
            case "idc":
                if (cfg.user?.group?.admin == true || cfg.user?.group?.Introduction == true) {
                    return true;
                } else {
                    return false;
                }
            default:
                return false;
        }
    },
    error: (error) => {
        cfg.alert3({
            message: `${error}`,
            closeOnClickOverlay: true,
        });
    },
    //？
    crkill: (cr, kill) => {
        let back = "";
        if (cr == 0.5) {
            if (kill == 1) {
                back = "尾刀";
            } else {
                back = "补偿";
            }
        } else {
            back = "整刀";
        }
        return back;
    },
    //加载公会
    load_gid: (gid) => {
        if (cfg.guild?.gid != null) {
            if (cfg.guild.gid == gid) {
                return;
            }
        }
        cfg.loadlist.guild = {
            name: "公会会战数据加载",
            file: {
                max: 0,
            },
            ok: true,
        };
        cfg.loadlist.season = {
            name: "会战赛季信息加载",
            file: {
                max: 0,
            },
            ok: true,
        };

        axios({
            method: 'get',
            url: `${cfg.url}?t=get/guild/data`,
            params: {
                gid: gid,
                type: "guild_info",
                authkey: cfg.user?.authkey
            },
            responseType: 'json',
            onDownloadProgress: function (progressEvent) {
                cfg.loadlist.guild.file.max = progressEvent.loaded;
            },
        })
            .then(response => {
                cfg.guild = response.data;
                delete cfg.loadlist.guild;
                cfg.guild.objuser = {};
                if (cfg.guild?.user_data?.length >= 1) {
                    cfg.guild.user_data.forEach(function (item) {
                        cfg.guild.objuser[item.user_id] = item.user_name;
                    });
                }
            })
            .catch(err => {
                cfg.alert3({
                    message: `${err}`,
                    closeOnClickOverlay: true,
                });
            });

        axios({
            method: 'get',
            url: `${cfg.url}?t=get/gt/season_list`,
            params: {
            },
            responseType: 'json',
            onDownloadProgress: function (progressEvent) {
                cfg.loadlist.guild.file.max = progressEvent.loaded;
            },
        })
            .then(response => {
                cfg.season = response.data;
                delete cfg.loadlist.season;
            })
            .catch(err => {
                cfg.alert3({
                    message: `${err}`,
                    closeOnClickOverlay: true,
                });
            });

    },
    //加载赛季列表
    season_list: async () => {
        try {
            const res = await axios.get(`${cfg.url}`, {
                params: {
                    t: "v2/get",
                    t2: "gt/season_list",
                    ckid: cfg.season.ckid ?? null,
                },
            });
            const data = res.data;
            if (data.code == -1) {
                //code 10000 重复数据 不需要更新
                if (data.cid == 10000) {
                    return false;
                }
            }

            cfg.season = {
                ...cfg.season,
                list: data.list,
                ckid: data.ckid,
                select: []
            };

            data.list.forEach((data2, key2) => {
                cfg.season.select.push({
                    value: parseInt(data2.sid),
                    label: `${data2.name}`,
                });
            });
            return true;
        } catch (error) {
            cfg.alert3({
                message: `${error}`,
                closeOnClickOverlay: true,
            });
        }
    },
    //更新路由
    uproute: (path, type, val) => {
        let arr = {};
        arr[type] = val;

        router.replace({
            path: path,
            query: arr
        })

    },

    ava: (ava, size) => {
        return `${cfg.url2}img/ava/${ava}@w${size ?? 72}_h${size ?? 72}.webp`;
    },
    botava: (url, ava) => {
        return `${url}/file?file=ava/${ava}`;
    },
    //退出登录
    loginout: () => {
        localStorage.removeItem('token');
        cfg.token = null;
        cfg.user = null;
    },
    //axios
    axs: async (url, get) => {
        return new Promise((resolve, reject) => {
            get.authkey = cfg.user.authkey;
            axios.get(`${cfg.url}${url}`, {
                params: get
            })
                .then(response => {
                    resolve(response.data);
                })
                .catch(error => {
                    reject(error);
                });
        });
    },
    //获取登录用户信息
    getuser: getuser,
    //忘了
    lgck: () => {

        if (!cfg.user.authkey) {
            cfg.login = true;
        } else {
            cfg.login = false;
        }

    },
    //随机字符串 (长度)
    rand: (length) => {
        let result = '';
        let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    },
    //保存登录authkey
    saveauthkey: (authkey) => {
        const localStorage = window.localStorage;
        localStorage.setItem('authkey', authkey)
        cfg.function.getuser(authkey);
    },
}